<template>
  <div>
    <el-card class="spu-card">
      <el-form
        label-width="100px"
        ref="spuFormRef"
        :model="spuFormData"
        :rules="spuFormRules"
      >
        <el-form-item label="SPU名称" prop="spuName">
          <el-input placeholder="SPU名称" v-model="spuFormData.spuName" />
        </el-form-item>
        <el-form-item label="品牌" prop="tmId">
          <el-select placeholder="请选择品牌" v-model="spuFormData.tmId">
            <el-option
              v-for="tm in trademarkList"
              :key="tm.id"
              :label="tm.tmName"
              :value="tm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" prop="description">
          <el-input
            placeholder="SPU描述"
            :rows="2"
            type="textarea"
            v-model="spuFormData.description"
          />
        </el-form-item>
        <el-form-item label="SPU图片" prop="spuImageList">
          <el-upload
            v-model:file-list="spuFormData.spuImageList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :action="UPLOAD_URL_PREFIX + '/admin/product/fileUpload'"
            :limit="MAX_LIMIT_LENGTH"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img :src="dialogImageUrl" alt="Preview Image" class="yulimg" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性" prop=" ">
          <el-select
            :placeholder="
              filterBaseSaleAttrList.length == 0
                ? '没有啦!'
                : `还剩${filterBaseSaleAttrList.length}个未选择`
            "
            v-model="selectedSaleAttr"
          >
            <el-option
              v-for="baseSaleAttr in filterBaseSaleAttrList"
              :key="baseSaleAttr.id"
              :label="baseSaleAttr.name"
              :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
            />
          </el-select>
          <el-button
            type="primary"
            :icon="Plus"
            class="spu-btn"
            @click="addSaleAttr"
            :disabled="!selectedSaleAttr"
          >
            添加销售属性
          </el-button>
          <el-table
            :data="spuFormData.spuSaleAttrList"
            border
            class="spu-table"
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              width="60"
            />
            <el-table-column label="属性名" prop="saleAttrName" width="200" />
            <el-table-column label="属性值名称列表" prop="xxx">
              <template v-slot="{ row }">
                <el-tag
                  closable
                  v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                  :key="saleAttrValue.saleAttrValueName"
                  class="spu-tag"
                  @close="delSaleAttrValue(row, index)"
                >
                  {{ saleAttrValue.saleAttrValueName }}
                </el-tag>
                <el-input
                  v-if="row.isEdit"
                  @blur="addSaleAttrValueName(row)"
                  @keyup.enter="addSaleAttrValueName(row)"
                  ref="inputRef"
                  v-model="saleAttrValueName"
                  class="spu-input"
                />
                <el-button v-else @click="showEdit(row)" :icon="Plus" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template v-slot="{ $index }">
                <el-tooltip
                  content="删除销售属性"
                  placement="top"
                  effect="light"
                >
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    @click="delSaleAttr($index)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="Cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "SaveOrUpdateSpu",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from "element-plus";
import { useCategoryStore } from "@/stores/category";

import {
  getBrandList,
  getSalesAttribute,
  saveSpuApi,
  getSpuSaleAttrListApi,
  getSpuImageListApi,
  updateSpuApi,
} from "@/Api/product/spu";
import type {
  getBrandListAray,
  SalesAttributeAray,
  SpuFormData,
  SpuSaleAttrItem,
  SpuImageItem,
} from "@/Api/product/model/spu";

const categoryStore = useCategoryStore();

const trademarkList = ref<getBrandListAray>([]);
const baseSaleAttrList = ref<SalesAttributeAray>([]);
onMounted(async () => {
  // Promise.all/allSettled
  trademarkList.value = await getBrandList();
});

onMounted(async () => {
  baseSaleAttrList.value = await getSalesAttribute();
});

onMounted(async () => {
  const { id } = spuFormData;
  // 添加不需要，更新才需要
  if (!id) return;
  const res = await getSpuImageListApi(id);
  spuFormData.spuImageList = res.map((img: SpuImageItem) => {
    return {
      name: img.imgName,
      url: img.imgUrl,
    };
  });
});

// 修改页面挂载的时候发送的销售属性的请求
onMounted(async () => {
  console.log(spuFormData);

  const { id } = spuFormData;
  // 添加不需要，更新才需要
  if (!id) return;
  spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
  console.log(spuFormData.spuSaleAttrList);
});

// 修改页面传过来渲染的数据
const props = defineProps<{
  spu: SpuFormData;
}>();

/****************** 照片墙 需要的数据或者方法  开始  ******************* */
// 存储图片的name和 url地址
// const fileList = ref<UploadUserFile[]>([]);

// 预览的 图片的  弹窗  和弹窗中的img中src地址
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

// 请求前缀
const UPLOAD_URL_PREFIX = import.meta.env.VITE_API_URL;
// 最大上传图片的数量
const MAX_LIMIT_LENGTH = 3;

// 上传按钮显示隐藏
const uploadBtnDisplay = computed(() => {
  return spuFormData.spuImageList.length < MAX_LIMIT_LENGTH
    ? "inline-flex"
    : "none";
});

/****************** 照片墙 需要的数据或者方法  结束  ******************* */

// 选中的销售属性
const selectedSaleAttr = ref("");

/********************************** 表单 form 验证 开始 ***************************** */
// 表单实例
const spuFormRef = ref<FormInstance>();
// 表单数据
const spuFormData = reactive<SpuFormData>(props.spu);
// spuName: "",
// tmId: undefined,
// description: "",
// spuImageList: [],
// spuSaleAttrList: [],

// spuFormData.spuImageList;
// 表单校验规则
const spuFormRules = reactive<FormRules>({
  spuName: [
    {
      required: true,
      message: "请输入SPU名称",
      trigger: "blur",
    },
  ],
  tmId: [
    {
      required: true,
      message: "请选择SPU品牌",
      trigger: "change",
    },
  ],
  description: [
    {
      required: true,
      message: "请输入SPU描述",
      trigger: "blur",
    },
  ],
  spuImageList: [
    {
      required: true,
      message: "请上传SPU图片",
      trigger: "blur",
    },
  ],
  spuSaleAttrList: [
    {
      required: true,
      message: "请选择SPU销售属性",
      trigger: "blur",
    },
  ],
});

/********************************** 表单 form 验证 结束 ***************************** */

// 添加销售属性
const addSaleAttr = () => {
  const [id, name] = selectedSaleAttr.value.split(":");

  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isEdit: false,
  });

  selectedSaleAttr.value = "";
};
// 销售属性
const filterBaseSaleAttrList = computed(() => {
  // 遍历所有基础销售属性列表，判断销售属性在不在table的数组（spuFormData.spuSaleAttrList)中
  // 在，过滤
  // 不在，保留
  return baseSaleAttrList.value.filter((baseSaleAttr) => {
    // 返回true保留，返回false是过滤
    /*
      {
        "baseSaleAttrId": 0, // 基础销售id
        "saleAttrName": "string", // 基础销售属性名称
        "spuSaleAttrValueList": [] // 销售属性值列表
      }
    */
    return !spuFormData.spuSaleAttrList.some(
      (saleAttr) => saleAttr.baseSaleAttrId === baseSaleAttr.id
    );
  });
});

// 删除销售属性
const delSaleAttr = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
};

const inputRef = ref();

// 点击显示模式的按钮进入编辑模式
const showEdit = async (row: SpuSaleAttrItem) => {
  row.isEdit = true;
  await nextTick();
  inputRef.value.focus();
};

// 收集的销售属性值名称
const saleAttrValueName = ref("");

// 编辑默认失去焦点，添加销售属性值
const addSaleAttrValueName = (row: SpuSaleAttrItem) => {
  if (saleAttrValueName.value) {
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: saleAttrValueName.value,
    });
    saleAttrValueName.value = "";
  }
  // 显示模式
  row.isEdit = false;
};

// 销售销售属性值
const delSaleAttrValue = (row: SpuSaleAttrItem, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};
const emit = defineEmits(["goSpuList"]);

// 提交表单  发送请求
const submitForm = async () => {
  // console.log(fileList);

  //提交表单
  await spuFormRef.value?.validate();

  const data = {
    ...spuFormData,
    tmId: spuFormData.tmId as number,
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        // imgUrl: (img.response as { data: string }).data,
        /*
          SaveOrUpdateSpu.vue:382 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
            at SaveOrUpdateSpu.vue:382:52

          更新：
            请求回来的图片只有url
            新上传的图片才有response.data

          判断是否是新上传的图片，是上传得到的图片地址 img.response.data
          不是，就用原有地址 img.url
        */

        imgUrl: img.response ? (img.response as any).data : img.url,
      };
    }),
    category3Id: categoryStore.category3Id as number,
  };
  if (spuFormData.id) {
    await updateSpuApi(data);
  } else {
    await saveSpuApi(data);
  }
  ElMessage.success(`${spuFormData.id ? "更新" : "添加"}SPU成功`);
  emit("goSpuList", 1);
};

// 取消按钮  返回到SpuTable 页面
const Cancel = () => {
  emit("goSpuList", 1);
};
</script>
<!-- @goSpuList="setIsShow" -->
<style scoped>
.spu-card {
  margin-top: 20px;
}

.spu-table {
  margin-top: 10px;
}

.spu-btn {
  margin-left: 10px;
}

.spu-card :deep(.el-upload) {
  display: v-bind(uploadBtnDisplay);
}

/* .spu-card :deep() {
  .el-upload {
    display: v-bind(uploadBtnDisplay);
  }
} */

.spu-card :deep(.el-dialog) {
  width: 700px;
}

.yulimg {
  width: 100%;
}

.spu-input {
  display: inline-block;
  width: 100px;
}

.spu-tag {
  margin-right: 10px;
}
</style>
